using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
using System.Security.Permissions;

namespace DDotNet.Data.BusinessObjects.Server
{
    /// <summary>
    /// This exception is returned from the 
    /// server-side DataPortal and contains the exception
    /// and context data from the server.
    /// </summary>
    [SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors")]
    [Serializable()]
    public class DataPortalException : Exception
    {
        private DataPortalResult _result;
        private string _innerStackTrace;

        /// <summary>
        /// Returns the DataPortalResult object from the server.
        /// </summary>
        public DataPortalResult Result
        {
            get { return _result; }
        }

        /// <summary>
        /// Get the server-side stack trace from the
        /// original exception.
        /// </summary>
        [
            SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider",
                MessageId = "System.String.Format(System.String,System.Object,System.Object,System.Object)")]
        public override string StackTrace
        {
            get
            {
                return String.Format("{0}{1}{2}",
                                     _innerStackTrace, Environment.NewLine, base.StackTrace);
            }
        }

        public DataPortalException(
            string message, Exception ex, DataPortalResult result)
            : base(message, ex)
        {
            _innerStackTrace = ex.StackTrace;
            _result = result;
        }

        protected DataPortalException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            _result = (DataPortalResult) info.GetValue(
                                             "_result", typeof (DataPortalResult));
            _innerStackTrace = info.GetString("_innerStackTrace");
        }

        [SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
        [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.SerializationFormatter)]
        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info, context);
            info.AddValue("_result", _result);
            info.AddValue("_innerStackTrace", _innerStackTrace);
        }
    }
}